import requests
import os
import sys
from pathlib import Path
import psutil


class Info:
    def __init__(self):
        self.version, self.url = self.get()

    @staticmethod
    def get():
        urls = [
            'https://launcher.mojang.com/v1/objects/952438ac4e01b4d115c5fc38f891710c4941df29/server.jar',  # 1.7.10
            'https://launcher.mojang.com/v1/objects/5fafba3f58c40dc51b5c3ca72a98f62dfdae1db7/server.jar',  # 1.8.8
            'https://launcher.mojang.com/v1/objects/886945bfb2b978778c3a0288fd7fab09d315b25f/server.jar',  # 1.12.2
            'https://launcher.mojang.com/v1/objects/1b557e7b033b583cd9f66746b7a9ab1ec1673ced/server.jar',  # 1.16.5
            'https://launcher.mojang.com/v1/objects/125e5adf40c659fd3bce3e66e67a16bb49ecc1b9/server.jar'  # 1.18.1
        ]
        versions = ['1.7.10', '1.8.8', '1.12.2', '1.16.5', '1.18.1']
        ver = int(input('1. 1.7.10\n'
                        '2. 1.8.8\n'
                        '3. 1.12.2\n'
                        '4. 1.16.5\n'
                        '5. 1.18.1\n'
                        '请输入要安装版本前的序号: \n'))

        return versions[ver - 1], urls[ver - 1]


# 下载服务器包
def download(info):
    class MCSpider:
        def __init__(self, ver, url):
            self.version = ver
            self.url = url

        def download(self):
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.76'
            }
            response = requests.get(self.url, headers=headers)
            with open(f'minecraft_server.{self.version}.jar', 'wb') as file:
                file.write(response.content)

        def file_exist(self):
            self.download()
            filename = f'minecraft_server.{self.version}.jar'
            file = Path(filename)
            if file.exists() and file.is_file():
                return True
            else:
                return False

    spider = MCSpider(info.version, info.url)
    if spider.file_exist():
        modify_eula(info)
    else:
        raise Exception('DownloadError')


# 生成并修改eula.txt
def modify_eula(info):
    eula_content = 'eula=true'
    with open('eula.txt', 'w') as eula_file:
        eula_file.write(eula_content)
    start(info)


# 启动服务器
def start(info):
    class Value:
        def __init__(self, name, val='', unit='M'):
            self.name = name
            self.val = val
            self.unit = unit
            self.set_value()

        def set_value(self):
            self.val = input(f'请输入{self.name}的值（输入时请加上大写单位M或G，否则默认M为单位；回车代表默认值1024M）：\n')
            if self.val == '':
                self.val = '1024M'
            else:
                mem = psutil.virtual_memory()
                MB = 1024 * 1024
                GB = 1024 * 1024 * 1024
                if self.val.isdigit() is False:
                    self.unit = self.val[-1]
                    self.val = self.val.replace(self.unit, '')
                if self.unit == 'M':
                    if int(self.val) > int(mem.total / MB):
                        print(f'警告！你所设定的{self.name}值大于系统实际内存！请重新设置！')
                        self.set_value()
                    else:
                        self.val += self.unit
                elif self.unit == 'G':
                    if int(self.val) > int(mem.total / GB):
                        print(f'警告！你所设定的{self.name}值大于系统实际内存！请重新设置！')
                        self.set_value()
                    else:
                        self.val += self.unit

    xmx = Value('xmx')
    xms = Value('xms')
    create_bat(info, xmx, xms)
    os.system(f'java -Xmx{xmx.val} -Xms{xms.val} -jar minecraft_server.{info.version}.jar nogui')
    print('服务器已成功部署，下次启动服务器请运行服务器根目录下的start.bat')
    input('按任意键退出...')
    raise SystemExit


# 生成运行脚本
def create_bat(info, xmx, xms):
    with open('start.bat', 'w') as bat:
        bat.write(
            '@echo off\n'
            f'java -Xmx{xmx.val} -Xms{xms.val} -jar minecraft_server.{info.version}.jar nogui'
        )


if __name__ == '__main__':
    try:
        g_info = Info()
        download(g_info)
    except Exception as error:
        if error != SystemExit:
            print('error:', error)
        sys.exit()
